package com.kgc.scd.listener;/**
 * <p>
 *
 * </p>
 *
 * @author shelina
 * @since 2022/11/17
 */

import com.kgc.scd.bean.User;
import com.kgc.scd.conntant.WechatPayConstant;
import com.kgc.scd.service.WechatPayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

/**
 * Created On : 2022/11/17.
 * <p>
 * Author : #jiangguoqiang
 * <p>
 * Description: 监听过期时间,KeyExpirationEventMessageListener监听过期时间，服务器集群情况
 */
@Slf4j
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    @Autowired(required = false)
    private WechatPayService wechatPayService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 针对 redis 数据失效事件，进行数据处理
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        //创建user实体
        User user = new User();
        // 获取到失效的 key，进行业务处理
        String expiredKey = message.toString();
        log.info("------ 监听redis失效队列,更新用户会员信息 ------");
        if (expiredKey.contains(WechatPayConstant.REDIS_MEMBER_UNIFIED_PREFIX)){
            expiredKey = expiredKey.substring(4, expiredKey.length());
            log.info("------ 用户编号：{} 的用户的会员已失效，更新用户信息 ------",expiredKey);
            user.setUserLevelId(false);
            user.setId(expiredKey);
            log.info("------ 更新用户信息成功 ------");
            wechatPayService.modUser(user);
        }
    }
}
